/**
 * @description api
 *
 * @author xiaomi
 */

const koa = require('koa');
const cors = require('koa-cors');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cacheControl = require('./lib/koa-cache-control');
const ctrls = require('./controllers/api');
const app = koa();

// init models
app.models = require('./models');

// bodyParser
app.use(bodyParser({
    formLimit: '1mb',
    jsonLimit: '1mb'
}));

// cacheControl
app.use(cacheControl({
    noCache: true
}));

// build docs
if(process.env.NODE_ENV === 'development') {
    require('./components/doc-builder')();
}

// init router
app.router = new Router();

// signature
const signatureMW = require('./lib/koa-signature');
// app.router.use(signatureMW({
//     allowedIps: process.env.API_IP_WHITELIST.split(','),
//     production: !(process.env.API_HOST.indexOf('.dev') > -1),
//     allowedApps: require('./data/subapps')
// }));

// cors
// app.use(app.router.allowedMethods());
app.use(cors({
    origin: true,
    credentials: true,
    maxAge: 7 * 24 * 60 * 60,
    headers: ['Content-Type', 'Authorization', 'X-Appid', 'X-Timestamp', 'X-Signature', 'X-DeviceID'],
    // headers: ['Authorization', 'X-Api-Version', 'X-Signature'],
    // expose: ['WWW-Authenticate', 'X-Pagination']
    expose: ['X-Pagination']
}));

// passport
const passport = require('./services/passport');
app.use(passport.initialize());
app.use(passport.session());
// init ctrls
ctrls.forEach(ctrl => ctrl(app, app.router));

// use routers
app.use(app.router.routes());

module.exports = app;
